﻿using AutoMapper;
using ClosedXML.Excel;
using Dapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using MyMES.Domain.W.Liststructure;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Incominginformations;
using MyMES.Read.API.Dtos;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.Text;

namespace MyMES.Read.API.Controllers.ZMC.Incominginformations
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class IncominginformationsController : ControllerBase
    {

        private readonly IMediator mediator;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Arrivalnotice> arrivalnotRepository;
        private readonly IBaseRepository<Supplier> supplierRepository;
        private readonly IBaseRepository<Incominginformation> incomRepository;
        private readonly IBaseRepository<StoragePurchase> istoRepository;
        public DatabaseContext db;

        public IncominginformationsController(IMediator mediator, IMapper mapper, IBaseRepository<Arrivalnotice> arrivalnotRepository, IBaseRepository<Supplier> supplierRepository, IBaseRepository<Incominginformation> incomRepository, IBaseRepository<StoragePurchase> istoRepository, DatabaseContext db)
        {
            this.mediator = mediator;
            this.mapper = mapper;
            this.arrivalnotRepository = arrivalnotRepository;
            this.supplierRepository = supplierRepository;
            this.incomRepository = incomRepository;
            this.istoRepository = istoRepository;
            this.db = db;
        }




        /// <summary>
        /// 获取供应商列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<Supplier>>> GetSupplier([FromQuery] GetSupplierCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        /// <summary>
        /// 获取到货通知单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<ArrivalnoSupplierDtos>>> GetArrivalnotice([FromQuery] GetArrivalnoticeCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<IncomArrivaSuppDtos>>> GetIncominginformations([FromQuery]GetIncominginformationsCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 采购入库信息导出
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<IActionResult> ExeclIncomArriva()
        {
            try
            {
                APIResult<IncomArrivaSuppDtos> result = new APIResult<IncomArrivaSuppDtos>();
                result.Code = APIEnum.查询成功;
                result.Msg = "采购入库信息导出成功";
                var sql = "SELECT a.*,b.NoticeName,c.SupplierName,d.StoragePurchaseNo FROM incominginformation a LEFT JOIN arrivalnotice b on a.noticeId=b.NoticeId  LEFT JOIN supplier c on a.SupplierId=c.SupplierId   LEFT JOIN storagepurchase d on a.StoragePurchaseId=d.StoragePurchaseId    where IsDlete=false ORDER BY a.StorageId DESC;";

                var incoms = await incomRepository.SelectAsync(sql);
                var arrivas = await arrivalnotRepository.SelectAsync(sql);
                var supps = await supplierRepository.SelectAsync(sql);
                var stos = await istoRepository.SelectAsync(sql);
                var rincom = mapper.Map<List<IncomArrivaSuppDtos>>(incoms);
                var rarriva = mapper.Map<List<IncomArrivaSuppDtos>>(arrivas);
                var rsupp = mapper.Map<List<IncomArrivaSuppDtos>>(supps);
                var rstos = mapper.Map<List<IncomArrivaSuppDtos>>(stos);

                //循环赋值
                foreach (var item in rincom)
                {

                    item.SupplierName = rsupp.FirstOrDefault(x => x.SupplierId == item.SupplierId)?.SupplierName;
                    item.NoticeName = rarriva.FirstOrDefault(x => x.noticeId == item.noticeId)?.NoticeName;
                    item.StoragePurchaseNo = rstos.FirstOrDefault(x => x.StoragePurchaseId == item.StoragePurchaseId).StoragePurchaseNo;
                }
                var Rlist = await incomRepository.SelectAsync(sql);

                //创建工作簿
                IWorkbook workbook = new XSSFWorkbook();

                //依据工作簿创建sheet
                ISheet sheet = workbook.CreateSheet("采购入库信息");
                //依据sheet创建首行
                IRow row = sheet.CreateRow(0);
                //在创建好的行中创建首行单元格
                row.CreateCell(0).SetCellValue("入库单编号");
                row.CreateCell(1).SetCellValue("入库单名称");
                row.CreateCell(2).SetCellValue("供应商名称");
                row.CreateCell(3).SetCellValue("入库日期");
                row.CreateCell(4).SetCellValue("采购订单号");
                row.CreateCell(5).SetCellValue("删除标志位");




                //行编号
                int index = 1;
                foreach (var item in rincom.ToList())
                {
                    //sheet表中的第二行完成数据遍历
                    //创建新行
                    row = sheet.CreateRow(index);
                    var isdete = item.IsDlete == false ? "否" : "是";
                    //将所有数据依次写入到行中
                    row.CreateCell(0).SetCellValue(item.StorageNo);
                    row.CreateCell(1).SetCellValue(item.StorageName);
                    row.CreateCell(2).SetCellValue(item.SupplierName);
                    row.CreateCell(3).SetCellValue(item.StorageDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(4).SetCellValue(item.StoragePurchaseNo);
                    row.CreateCell(5).SetCellValue(isdete);

                    //item.StartDate.HasValue ? item.StartDate.Value.ToString("yyyy-MM-dd") : ""
                    //换行
                    index++;
                }

                //excel
                byte[] buffer;
                //使用内存流出Excel的内容
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }
                //导出Excel  using Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];


                //导出
                return File(buffer, excelMime, "采购入库信息.xlsx");
            }
            catch (Exception)
            {

                throw;
            }




        }



        /// <summary>
        /// 查询物料入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<APIResult<List<Materialmanagement>>> GetMaterialmanagementIncominginfor([FromQuery]GetMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取物料入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<MateArrivaDtos>>> GetMateArriva([FromQuery]GetMateArrivaCommends request, CancellationToken cancellationToken)
        {

            return await mediator.Send(request, cancellationToken);
        }





    }
}
